# 编号: bid
# 书名: name
# 价格: price
# 简介: summary
import os
import time

import yaml

class Book:
    def __init__(self, bid, name, price, summary):
        self.bid = bid
        self.name = name
        self.price = price
        self.summary = summary
    def __str__(self):
        return f'编号: {self.bid},书名: {self.name},价格: {self.price},简介: {self.summary}'
class BookManagement:
    def __init__(self):
        self.__books = []
        self.load_data()
    def manager(self):
        while True:
            self.__menu()
            select = input("输入编号选择操作（1-8之间的数字）：")
            if select == "1":
                self.__add_book()
            elif select == "2":
                self.modify_book_by_id()
            elif select == "3":
                self.delete_book_by_id()
            elif select == "4":
                self.delete_book_by_name()
            elif select == "5":
                print(self.query_book_by_id())
            elif select == "6":
                print(self.query_book_by_name())
            elif select == "7":
                self.show()
            elif select == "8":
                print("正在保存数据...")
                self.save_data()  # 退出前先保存数据
                print("已退出系统！")
                break
            else:
                print('输入有误,请重新输入')
    def __menu(self):
        print("*****************************")
        print("*      图书管理系统           *")
        print("* 1. 添加新图书信息           *")
        print("* 2. 通过编号修改图书信息      *")
        print("* 3. 通过编号删除图书信息      *")
        print("* 4. 通过书名删除图书信息      *")
        print("* 5. 通过编号查询图书信息      *")
        print("* 6. 通过书名查询图书信息      *")
        print("* 7. 显示所有图书信息         *")
        print("* 8. 退出系统                *")
        print("*****************************")
    def __get_bid(self):
        bid = input('请输入编号:')
        return bid
    def __get_name(self):
        name = input('请输入书名:')
        return name
    def __get_price(self):
        price = input('请输入价格:')
        return price
    def __get_summary(self):
        summary = input('请输入介绍:')
        return summary
    def __add_book(self):
        bid = self.__get_bid()
        for book in self.__books:
            if book.bid == bid:
                print('编号已存在,添加失败')
                return '添加失败'
        name = self.__get_name()
        price = self.__get_price()
        summary = self.__get_summary()
        self.__books.append(Book(bid, name, price, summary))
        print('添加成功')
        return '添加成功'
    def modify_book_by_id(self):
        bid = self.__get_bid()
        for book in self.__books:
            if book.bid == bid:
                book.name = self.__get_name()
                book.price = self.__get_price()
                book.summary = self.__get_summary()
                print('修改成功')
                return '修改成功'
        print('编号不存在,修改失败')
        return '修改失败'
    def delete_book_by_id(self):
        bid = self.__get_bid()
        for book in self.__books:
            if book.bid == bid:
                self.__books.remove(book)
                print(f"成功删除 {book.name} 的信息")
                return "删除成功"
        print('编号不存在,删除失败')
        return "删除失败"
    def delete_book_by_name(self):
        name = self.__get_name()
        names = []
        for book in self.__books:
            if book.name == name:
                names.append(book)
        if len(names) > 0:
            for s in names:
                self.__books.remove(s)
                print(f"书名为 {name} 的书籍删除成功 ")
            print(f"成功删除 {len(names)} 个信息")
            return "删除成功"
        else:
            print(f"书名为 {name} 的书籍不存在，无法删除")
            return "删除失败"
    def query_book_by_id(self):
        bid = self.__get_bid()
        for book in self.__books:
            if book.bid == bid:
                return book
        return '编号不存在'
    def query_book_by_name(self):
        name = self.__get_name()
        for book in self.__books:
            if book.name == name:
                return book
        print('书面不存在')
        return '书面不存在'
    def show(self):
        for book in self.__books:
            print(book)
    def save_data(self):
        filename = 'data.yml'
        book_data = [{'bid': b.bid, 'name': b.name, 'price': b.price, 'summary': b.summary}
                     for b in self.__books]
        with open(os.getcwd() + "/data/" + filename, encoding="utf-8", mode="w") as f:
            yaml.safe_dump(book_data, stream=f)
    def load_data(self):
        filename = 'data.yml'
        with open(os.getcwd() + "/data/" + filename, encoding="utf-8", mode="r") as f:
            book_data = yaml.safe_load(f)
        if not book_data:  # 覆盖 None 或 空列表 [] 的情况
            self.__books = []
            print("数据文件为空，已初始化空图书列表")
            return
        self.__books = [Book(bid=item['bid'],name=item['name'],price=item['price'],summary=item['summary']) for item in book_data]
if __name__ == '__main__':
    book = BookManagement()
    book.manager()
